package com.bw.gateway.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.CoreSubscriber;
import reactor.core.publisher.Mono;

/**
 * 获取请求服务的执行时间
 */
@Component
@Order(1)
@Slf4j
public class MyFilter extends AbstractGatewayFilterFactory {
    private static final  String BEGIN_TIME = "begin_time";
    @Override
    public GatewayFilter apply(Object config) {
        return (exchange,  chain)->{
            long beginTime = System.currentTimeMillis();
            exchange.getAttributes().put(BEGIN_TIME,beginTime);
            return chain.filter(exchange).then(Mono.fromRunnable(()->{
                Object o = exchange.getAttributes().get(BEGIN_TIME);
                if (o!=null){
                    Long begin_time = (Long)o;
                    log.info("服务{}:消耗了多长时间{}  ms",exchange.getRequest().getURI().toString(),System.currentTimeMillis()-beginTime);
                }
            }));
        };
    }
}
